package com.xctech.iot.mqtt.sdk.publish;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <pre>
 * 服务启动成功后，发布者连接mqtt
 * </pre>
 *
 * @author: feihu.liang
 * @since: 2024/4/11 14:39
 */
@Slf4j
@Component
public class MqttPublisherApplicationRunner implements ApplicationRunner {

    private ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
    private ScheduledFuture scheduledFuture;

    @Autowired
    private MqttPublisher mqttPublisher;

    @Override
    public void run(ApplicationArguments args) {
        try {
            mqttPublisher.connect();
        } catch (Exception e) {
            log.error("[run] connect error=", e);
            startReconnect();
        }
    }

    /**
     * <pre>
     * 重新建立连接
     * </pre>
     *
     * @return
     * @date 2021/10/18 10:34:37
     */
    public void startReconnect() {
        scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(() -> {
            if (!mqttPublisher.isConnected()) {
                log.info("[startReconnect] start reconnecting");
                mqttPublisher.reconnect();
            } else {
                if (scheduledFuture != null && !scheduledFuture.isDone()) {
                    scheduledFuture.cancel(true);
                }
            }
        }, 0, 30, TimeUnit.SECONDS);
    }

}
